import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store/index';
import { setItem, getItem } from '@/utils/componen';

// ==================== 基础路由配置 ====================
const staticRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
    },
  },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '主页',
    },
    children: [],
  },
];

// ==================== 动态路由相关 ====================
const routeComponents = import.meta.glob('../views/**/index.vue');
const pageMetas = import.meta.glob('../views/**/page.ts', {
  eager: true,
  import: 'default',
});

const nonChildRoutes = ['404', 'login', 'add', 'details'];
const dynamicRoutePaths: string[] = [];

/**
 * 根据 page.ts 文件动态生成路由对象并添加到对应父级路由中
 */
function generateAndAddRoute(path: string, meta: any): void {
  const compPath = path.replace('page.ts', 'index.vue');
  const routePath = path.replace('../views', '').replace('/page.ts', '') || '/';
  const routeName = routePath.split('/').filter(Boolean).join('-') || 'index';

  const route: RouteRecordRaw = {
    path: routePath,
    name: routeName,
    component: routeComponents[compPath],
    meta,
  };

  if (nonChildRoutes.includes(routeName)) {
    staticRoutes.push(route);
  } else {
    const layoutRoute = staticRoutes.find((r) => r.name === 'layout');
    if (layoutRoute && layoutRoute.children) {
      layoutRoute.children.push(route);
    }
  }

  dynamicRoutePaths.push(routePath);
}

// 遍历所有 page.ts 文件，构建动态路由
Object.entries(pageMetas).forEach(([filePath, meta]) => {
  generateAndAddRoute(filePath, meta);
});

// ==================== 创建路由实例 ====================
const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes,
});

// ==================== 路由守卫逻辑 ====================

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  userStore.routesArr = dynamicRoutePaths;

  // 设置页面标题
  document.title = to.meta.title ? `系统 - ${to.meta.title}` : '管理系统';

  const token = getItem('apiToken');

  // 白名单处理
  if (to.path === '/login' || token) {
    // 权限验证通过，继续导航
    if (dynamicRoutePaths.includes(to.path) || to.path === '/') {
      // 设置当前激活菜单
      if (!['/404', '/login'].includes(to.path)) {
        userStore.activeMenu = to.path;
        if (!to.path.includes('details')) {
          setItem('toPath', to.path);
        }
      }
      return next();
    } else {
      // 无权限或不存在的路由跳转至 404
      if (userStore.menuTab.length > 1) {
        userStore.menuTab.pop();
        setItem('menuTab', userStore.menuTab);
      }
      return next('/404');
    }
  } else {
    // 未登录清除本地数据并跳转登录页
    localStorage.clear();
    ElMessage.warning('请先登录');
    return next('/login');
  }
});

// ==================== 导出 ====================
export default router;
